import 'dart:async';
import 'dart:convert';
import 'package:get/get.dart';
import 'package:flutter/material.dart';
import 'package:http_manager/http_manager.dart';
import '../../../utils/common/app_launching.dart';
import '../../../utils/widget/common.dart';
import '../controllers/login_controller.dart';
import 'background.dart';

class LoginView extends GetView<LoginController> {
  const LoginView({super.key});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      resizeToAvoidBottomInset: true,
      body: setupSubViews(),
    );
  }

  setupSubViews() {
    return ServerpodBackground(
      child: Column(
        children: [
          buildLoginView(),
          const Spacer(),
          const GestureDemo(),
          const SizedBox(height: 20),
        ],
      ),
    );
  }

  Widget buildLoginView() {
    return Container(
      margin: const EdgeInsets.only(left: 25, right: 25, top: 200),
      decoration: BoxDecoration(
        color: Colors.white.withOpacity(0.85),
        borderRadius: BorderRadius.circular(20),
        boxShadow: [
          BoxShadow(
            color: Colors.black.withOpacity(0.1),
            blurRadius: 20,
            spreadRadius: 0,
            offset: const Offset(0, 10),
          ),
        ],
      ),
      child: SingleChildScrollView(
        child: Column(
          children: [
            const SizedBox(height: 20),
            // 标题
            Text(
              "欢迎登录",
              style: TextStyle(
                fontSize: 18,
                fontWeight: FontWeight.bold,
                color: ThemeColor,
              ),
            ),
            const SizedBox(height: 10),
            // 表单
            buildLoginForm(),
            const SizedBox(height: 15),
            // 登录按钮
            buildLoginButton(),
            const SizedBox(height: 15),
            // 其他选项
            // buildAdditionalOptions(),
            const SizedBox(height: 10), // 添加底部间距
          ],
        ),
      ),
    );
  }

  Widget buildLoginForm() {
    return Padding(
      padding: const EdgeInsets.symmetric(horizontal: 10),
      child: Column(
        children: [
          // 账号输入框
          buildTextField(
            controller: controller.accountVC,
            hintText: "请输入账号或手机号",
            prefixIcon: Icons.person_outline,
            onChanged: (value) {
              controller.canLogin.value = controller.accountVC.text.isNotEmpty && 
                controller.passwordVC.text.isNotEmpty &&
                controller.shortCodeVC.text.isNotEmpty;
            },
          ),
          const SizedBox(height: 15),
          // 密码输入框
          buildTextField(
            obscureText: true,
            hintText: "请输入密码",
            prefixIcon: Icons.lock_outline,
            controller: controller.passwordVC,
            onChanged: (value) {
              controller.canLogin.value = controller.accountVC.text.isNotEmpty && 
                controller.passwordVC.text.isNotEmpty &&
                controller.shortCodeVC.text.isNotEmpty;
            },
          ),
          const SizedBox(height: 15),
          // 验证码
          buildCaptchaRow(),
        ],
      ),
    );
  }

  Widget buildTextField({
    required TextEditingController controller,
    required String hintText,
    required IconData prefixIcon,
    bool obscureText = false,
    Function(String)? onChanged,
  }) {
    return Container(
      decoration: BoxDecoration(
        color: Colors.grey.withOpacity(0.1),
        borderRadius: BorderRadius.circular(10),
      ),
      child: TextField(
        controller: controller,
        obscureText: obscureText,
        decoration: InputDecoration(
          hintText: hintText,
          hintStyle: TextStyle(color: Colors.grey[400]),
          prefixIcon: Icon(prefixIcon, color: ThemeColor),
          border: InputBorder.none,
        ),
        style: const TextStyle(color: Colors.black87, fontSize: 14),
        onChanged: onChanged,
      ),
    );
  }

  Widget buildCaptchaRow() {
    return Row(
      children: [
        // 验证码输入框
        Expanded(
          child: Container(
            decoration: BoxDecoration(
              color: Colors.grey.withOpacity(0.1),
              borderRadius: BorderRadius.circular(10),
            ),
            child: TextField(
              controller: controller.shortCodeVC,
              decoration: InputDecoration(
                hintText: "请输入验证码",
                hintStyle: TextStyle(color: Colors.grey[400]),
                prefixIcon: Icon(Icons.verified_user_outlined, color: ThemeColor),
                border: InputBorder.none,
              ),
              style: const TextStyle(color: Colors.black87, fontSize: 14),
              onChanged: (value) {
                controller.canLogin.value = controller.accountVC.text.isNotEmpty && 
                  controller.passwordVC.text.isNotEmpty &&
                  controller.shortCodeVC.text.isNotEmpty;
              },
            ),
          ),
        ),
        
        // 验证码图片
        const SizedBox(width: 15),
        Obx(() => GestureDetector(
          onTap: () => controller.refreshCaptcha(),
          child: Container(
            width: 120,
            decoration: BoxDecoration(
              borderRadius: BorderRadius.circular(10),
              color: Colors.grey.withOpacity(0.1),
            ),
            child: controller.isCaptchaLoaded.value 
              ? controller.captchaImage.value != null
                ? Image.memory(

                  base64Decode(controller.captchaImage.value!),
                  fit: BoxFit.scaleDown,
                )
                : Center(
                    child: Text(
                      "加载中...",
                      style: TextStyle(color: Colors.grey[600]),
                    ),
                  )
              : Center(
                  child: Text(
                    "点击刷新",
                    style: TextStyle(color: ThemeColor),
                  ),
                ),
          ),
        )),
      ],
    );
  }

  Widget buildLoginButton() {
    return Padding(
      padding: const EdgeInsets.symmetric(horizontal: 25),
      child: Obx(() => AnimatedContainer(
        duration: const Duration(milliseconds: 300),
        width: double.infinity,
        height: 50,
        decoration: BoxDecoration(
          gradient: controller.canLogin.value 
            ? LinearGradient(
                colors: [ThemeColor.withOpacity(0.8), ThemeColor],
                begin: Alignment.centerLeft,
                end: Alignment.centerRight,
              )
            : LinearGradient(
                colors: [Colors.grey.withOpacity(0.3), Colors.grey.withOpacity(0.5)],
                begin: Alignment.centerLeft,
                end: Alignment.centerRight,
              ),
          borderRadius: BorderRadius.circular(10),
          boxShadow: controller.canLogin.value
            ? [
                BoxShadow(
                  color: ThemeColor.withOpacity(0.3),
                  blurRadius: 10,
                  offset: const Offset(0, 5),
                )
              ]
            : [],
        ),
        child: Material(
          color: Colors.transparent,
          child: InkWell(
            borderRadius: BorderRadius.circular(10),
            onTap: controller.canLogin.value ? () => controller.loginClick() : null,
            child: Center(
              child: Text(
                "登录",
                style: TextStyle(
                  color: controller.canLogin.value ? Colors.white : Colors.grey[600],
                  fontSize: 16,
                  fontWeight: FontWeight.w600,
                ),
              ),
            ),
          ),
        ),
      )),
    );
  }

  Widget buildAdditionalOptions() {
    return Row(
      mainAxisAlignment: MainAxisAlignment.center,
      children: [
        TextButton(
          onPressed: () {
            // 处理忘记密码
          },
          child: Text(
            "忘记密码?",
            style: TextStyle(color: Colors.grey[600]),
          ),
        ),
        Container(
          height: 15,
          width: 1,
          color: Colors.grey[300],
        ),
        TextButton(
          onPressed: () {
            // 处理注册账号
          },
          child: Text(
            "注册账号",
            style: TextStyle(color: ThemeColor),
          ),
        ),
      ],
    );
  }

  // 隐私协议
  Widget setupPrivacyPolicy() {
    // web 端暂时不用协议
    controller.checkboxSelected.value = true;
    return Row(
      crossAxisAlignment: CrossAxisAlignment.center,
      mainAxisAlignment: MainAxisAlignment.start,
      children: [
        Checkbox(
            shape: const CircleBorder(),// 这⾥就是圆形
            side: const BorderSide(width: 1, color: ThemeColor),
            value: controller.checkboxSelected.value,
            activeColor: ThemeColor, //选中时的颜色
            onChanged:(value) => controller.checkboxClick(value)
        ),

        const Text("已阅读并同意",style: TextStyle(fontSize: 13, color: Colors.black87),),
        GestureDetector(
          behavior: HitTestBehavior.opaque,
          onTap: (){
            Get.toNamed("/WebViewPage", arguments: {
              // "url" : "https://wxapp.91dgj.com/vue/agreement?name=%E6%95%B0%E5%AD%97%E7%A4%BE%E5%8C%BA",
              "url" : "https://echelianhtml.ygxpt.com/agreement/index.html",
              "title" : "服务协议",
            });
          },
          child: const Text("《服务协议》",style: TextStyle(fontSize: 13, color: Colors.blueAccent),),
        ),
        const Text("和",style: TextStyle(fontSize: 13, color: Colors.black87),),
        GestureDetector(
          behavior: HitTestBehavior.opaque,
          onTap: (){
            Get.toNamed("/WebViewPage", arguments: {
              // "url" : "https://wxapp.91dgj.com/vue/ios/privacyProtocol?name=%E6%95%B0%E5%AD%97%E7%A4%BE%E5%8C%BA",
              "url" : "https://echelianhtml.ygxpt.com/privacy/index.html",
              "title" : "隐私政策",
            });
          },
          child: const Text("《隐私政策》",style: TextStyle(fontSize: 13,color: Colors.blueAccent),),
        ),
      ],
    );
  }

  Widget debugButton() {
    return GestureDetector(
      behavior: HitTestBehavior.opaque,
      child: Container(
        color: Colors.transparent,
        alignment: Alignment.topLeft,
        width: 100, height: 80,
      ),
      onTap: ()=> AppLaunching.changeNetworkBaseURL(),
      onDoubleTap: () {
        showAlertDialog(
            title: "联机调试",
            content: Column(
              children: [
                const SizedBox(height: 10,),
                Container(
                  padding: const EdgeInsets.fromLTRB(10, 20, 10, 0),
                  child: MarkView(title: "", controller: controller.hostVC, hintText: "请输入调试主机地址", bgColor: Colors.grey[100]),
                )
              ],
            ),
            confirm: () async {
              if (controller.hostVC.text.isEmpty) { showAlertMessage("请填写取消理由"); return; }
              AppLaunching.changeNetworkBaseURL(host: controller.hostVC.text);
              dismissAlertDialog();
            },
            cancel: () {
              controller.hostVC.text = "";
              dismissAlertDialog();
            }
        );

      },
    );
  }
}

class GestureDemo extends StatefulWidget {
  const GestureDemo({super.key});
  @override
  _GestureDemoState createState() => _GestureDemoState();
}

class _GestureDemoState extends State<GestureDemo> {
  int _tapCount = 0;
  int _pointerCount = 0;
  Timer? _tapTimer;
  DateTime _lastTapTime = DateTime.now();

  void _handleTap() {
    final now = DateTime.now();
    final diff = now.difference(_lastTapTime);
    _lastTapTime = now;

    if (_tapTimer != null && _tapTimer!.isActive) {
      _tapTimer!.cancel();
    }

    if (diff.inMilliseconds > 300) {
      _tapCount = 0;
    }

    _tapCount++;

    if (_pointerCount == 2) {
      _tapTimer = Timer(const Duration(milliseconds: 300), () {
        if (_tapCount == 1) {
          AppLaunching.changeNetworkBaseURL();
          setState(() { });
          debugPrint('双指单击');
        } else if (_tapCount == 2) {
          _setupHost();
          debugPrint('双指双击');
        } else if (_tapCount == 3) {
          _configProxyPage();
          debugPrint('双指三击');
        }
        _tapCount = 0;  // Reset the count after handling the tap

      });
    }
  }

  void _setupHost() {
    final hostVC = TextEditingController(text: "192.168.");
    showAlertDialog(
        title: "联机调试",
        content: Column(
          children: [
            Text("请输入调试的主机地址\n例如：192.168.0.46:70", style: greyStyle(font: 16)),
            const SizedBox(height: 6),
            MarkView(title: "", controller: hostVC, height: 32, hintText: "请输入联机地址", bgColor: Colors.grey[100])
          ],
        ),
        confirm: () async {
          AppLaunching.changeNetworkBaseURL(host: hostVC.text);
          dismissAlertDialog();
          setState(() { });
        },
        confirmText: "开始联机",
        cancelText: "取消联机",
        cancel: () {
          AppLaunching.changeNetworkBaseURL();
          dismissAlertDialog();
          setState(() { });
        }
    );
  }

  void _configProxyPage() {
    final hostVC = TextEditingController(text: "192.168.");
    final portVC = TextEditingController(text: "8888");
    showAlertDialog(
        title: "请输入代理",
        content: Column(
          children: [
            // const SizedBox(height: 10,),
            MarkView(title: "", controller: hostVC, height: 32, hintText: "请输入代理地址", bgColor: Colors.grey[100]),
            const SizedBox(height: 10,),
            MarkView(title: "", controller: portVC, height: 32, hintText: "请输入端口号", bgColor: Colors.grey[100]),
          ],
        ),
        confirm: () async {
          HttpManager.setProxy(host: hostVC.text, port: portVC.text);
          showMessage("代理设置成功");
          dismissAlertDialog();
        },
        confirmText: "开启联机",
        cancelText: "关闭代理",
        cancel: () {
          HttpManager.setProxy();
          dismissAlertDialog();
        }
    );
  }

  @override
  Widget build(BuildContext context) {
    bool localhost = false;
    final baseUrl = HttpManager.baseUrl;
    if (baseUrl.startsWith("http://192.168.")) {
      localhost = true;
    }
    const title = "正式、测试环境，请双指单击\n自定义主机环境，请双指双击\n添加代理，请双指三连击\n本按钮仅192.168.x.x时显示";
    return Listener(
        onPointerDown: (PointerDownEvent event) {
          _pointerCount++;
          if (_pointerCount == 2) {
            _handleTap();
          }
        },
        onPointerUp: (PointerUpEvent event) => _pointerCount = 0,
        child: Container(
          margin: const EdgeInsets.fromLTRB(0, 5, 0, 0),
          padding: const EdgeInsets.fromLTRB(50, 50, 50, 50),
          decoration: BoxDecoration(
            borderRadius: BorderRadius.circular(8),
            color: localhost ? Colors.blue : Colors.transparent,
          ),
          child: localhost ? Text(title, style: whiteStyle(font: 16)) : const Text(""),
        )
    );
  }
}

